<template>
  <div
    v-loading="pageLoading"
    class="app-container"
    style="display: flex; flex-direction: column"
  >
    <!-- 搜索项 -->
    <!-- <div class="catalog">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        background-color="transparent"
        text-color="#2979ff"
        @select="handleSelect"
      >
        <el-menu-item
          v-for="(item, itemIndex) in pageList"
          :key="item.id"
          :index="itemIndex + ''"
          >{{ item.itemLabel }}</el-menu-item
        >
      </el-menu>
    </div> -->
    <div class="search-container" style="padding: 18px 15px 0">
      <el-form :model="searchParam" :inline="true" label-width="67px">
        <el-form-item label="工段">
          <el-select
            v-model="searchParam.workshopSectionId"
            placeholder="请选择工段"
            clearable
            filterable
            @change="changeWorkshopSection"
          >
            <el-option
              v-for="item in workshopSectionList"
              :key="item.id"
              :label="item.workshopSectionCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="车间">-->
        <!--          <el-select-->
        <!--            v-model="searchParam.workShopId"-->
        <!--            placeholder="请选择车间"-->
        <!--            clearable-->
        <!--            filterable-->
        <!--            @change="workShopChange"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in workshopIdList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.workshopName"-->
        <!--              :value="item.id"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processCodeList"
              :key="item.id"
              :label="item.processName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产线">
          <el-select
            v-model="searchParam.processEquipId"
            placeholder="请选择生产线"
            clearable
            filterable
            @change="equipChange"
            :filter-method="customFilter"
          >
            <el-option
              v-for="item in filteredOptions"
              :key="item.id"
              :label="item.equipName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select
            v-model="searchParam.deviceStatus"
            placeholder="请选择设备状态"
            clearable
          >
            <el-option
              v-for="item in produceStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetParams"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="0">
      <!-- <el-col :lg="cardGrid.lg" :md="cardGrid.md" :sm="24" :xs="24"> -->
      <el-col :lg="24" :md="24" :sm="24" :xs="24">
        <!-- 卡片内容 -->
        <div
          class="bg-#fff !pb-[10px] of-hidden rounded-[8px]"
          style="min-height: 250px"
          v-loading="loading"
        >
          <el-empty
            v-if="!tableData.length && !loading"
            :image-size="200"
            :image="pic3"
          />

          <div class="table-container-scroll pl-[5px] pr-[5px]">
            <ul>
              <li
                v-for="(self, selfIndex) in tableData"
                :key="selfIndex"
                @click="jumpUrl(self, 4)"
              >
                <div class="card-item">
                  <div
                    class="card-white-title"
                    :class="
                      self.deviceStatus == '3'
                        ? `redColor`
                        : self.deviceStatus == '2'
                        ? `greyColor`
                        : self.deviceStatus == '1'
                        ? `greenColor`
                        : ``
                    "
                  >
                    <!-- <span
                      >{{ self.processEquipCode }} -
                      {{ self.machineName }}</span
                    > -->
                    <span>{{ self.processEquipCode }}</span>
                    <span class="location-name">
                      <!-- {{
                        useDictionary(
                          "ProduceDeviceStatus",
                          self?.deviceStatus || ""
                        )
                      }} -->
                      <svg-icon
                        v-if="self.deviceStatus == '1'"
                        icon-class="face1"
                        class="face_svg"
                      />
                      <svg-icon
                        v-if="self.deviceStatus == '2'"
                        icon-class="face2"
                        class="face_svg"
                      />
                      <svg-icon
                        v-if="self.deviceStatus == '3'"
                        icon-class="face3"
                        class="face_svg"
                      />
                    </span>
                  </div>

                  <div class="card-content">
                    <div class="card-left">
                      <div class="pic-type">
                        <div
                          class="coverImg"
                          v-if="self.imgUrl"
                          :style="{
                            backgroundImage: `url(${actionUrl}/system/fileCenter/preview/${self.imgUrl})`,
                          }"
                        ></div>
                        <div
                          class="coverImg nodataImg"
                          v-if="!self.imgUrl"
                        ></div>

                        <svg-icon
                          :icon-class="
                            self.deviceStatus == '3'
                              ? `guzhang`
                              : self.deviceStatus == '2'
                              ? `tingchan`
                              : ``
                          "
                        />
                      </div>
                      <div class="link-type flex w-full">
                        <div class="m-1 text-[12px]! c-[#31343b]! flex-1">
                          <div>标准节拍</div>
                          <div>{{ self.standardTactTime ?? "-" }}</div>
                        </div>
                        <div class="m-1 text-[12px]! c-[#31343b]! flex-1">
                          <div>实际节拍</div>
                          <div>{{ self.actualTactTime ?? "-" }}</div>
                        </div>
                        <!-- <el-link
                          type="primary"
                          class="m-1 text-[12px]! link-btn"
                          @click="jumpUrl(self, 4)"
                          >工艺参数</el-link
                        > -->
                        <!-- <el-link
                          type="primary"
                          class="m-1 text-[12px]!"
                          @click="jumpUrl(self, 3)"
                          >产品列表</el-link
                        > -->
                        <!-- <el-link
                          type="primary"
                          class="m-1 text-[12px]!"
                          @click="jumpUrl(self, 2)"
                          >加工参数</el-link
                        >
                        <el-link
                          type="primary"
                          class="m-1 text-[12px]!"
                          @click="jumpUrl(self, 3)"
                          >过程参数</el-link
                        > -->
                      </div>
                    </div>
                    <div class="card-right">
                      <!-- <p class="card-name">
                        <span>客户</span
                        ><span class="numberLight">{{
                          self?.projectName || "--"
                        }}</span>
                      </p>
                      <p class="card-name">
                        <span>产品型号</span
                        ><span class="numberLight">{{
                          self?.productCode || "--"
                        }}</span>
                      </p> -->
                      <p class="card-name">
                        <span>产品型号</span
                        ><span class="numberLight">{{
                          self?.productCode || "--"
                        }}</span>
                      </p>
                      <p class="card-name">
                        <span>型号描述</span
                        ><span class="numberLight">{{
                          self?.productName || "--"
                        }}</span>
                      </p>
                      <!-- <p class="card-name">
                        <span>设备状态</span
                        ><span class="numberLight">{{
                          useDictionary(
                            "ProduceDeviceStatus",
                            self?.deviceStatus || ""
                          )
                        }}</span>
                      </p> -->
                      <div
                        class="card-name"
                        :class="
                          self.paramStatus == '3'
                            ? `redColor`
                            : self.paramStatus == '2'
                            ? `yellowColor07`
                            : ``
                        "
                      >
                        <span class="name-label">工单状态</span>
                        <div class="numberLight flex justify-center mt-[3px]">
                          <div
                            v-if="
                              !self.notClosedOrderCount &&
                              !self.timeoutOrderCount
                            "
                            class="flex h-[15px]"
                          >
                            <span
                              class="inline-block! bg-[#1De9b6] w-[13px]! h-[13px] rounded-[13px] mt-[1px]"
                            ></span>
                          </div>
                          <div
                            v-if="self.notClosedOrderCount"
                            class="flex h-[15px]"
                          >
                            <span
                              class="inline-block! bg-yellow w-[13px]! h-[13px] rounded-[13px] mt-[1px]"
                            ></span>
                            <span class="m-0! ml-[4px]!">{{
                              self.notClosedOrderCount
                            }}</span>
                          </div>

                          <div
                            v-if="self.timeoutOrderCount"
                            class="flex h-[15px]"
                            :class="self.notClosedOrderCount ? 'ml-[16px]' : ''"
                          >
                            <span
                              class="inline-block! bg-red w-[13px]! h-[13px] rounded-[13px] mt-[1px]"
                            ></span>
                            <span class="m-0! ml-[4px]!">{{
                              self.timeoutOrderCount
                            }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
            </ul>

            <!-- 分页 -->
            <el-pagination
              :background="true"
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[30px] ml-[10px] mb-2"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import request from "@/utils/request";
import pic3 from "@/assets/images/noData2.png";
import { useRoute, useRouter } from "vue-router";
import { mockList1 } from "./index";
import { useTable, useDictionary } from "@/utils/useTable";
import {
  getMdmProcessEquipApi1,
  getMdmProcessEquipApi2,
} from "@/utils/commonData";
import _ from "lodash-es";

const router = useRouter();

defineOptions({
  name: "PSMPSMPARAMMONITORING",
  inheritAttrs: false,
});

// 图片地址
const actionUrl = import.meta.env.VITE_APP_BASE_API;

/*
  设备监控列表 — 数据定义
*/
const pageList: any = ref([]);
const pageLoading = ref(false);
const deviceLoading = ref(false);

/*
  设备监控列表 — 页签点击事件
*/
const activeIndex = ref("0");
const handleSelect = (key: string) => {
  activeIndex.value = key;
  const itemValue = pageList.value[key].itemValue;

  getDeviceList(itemValue);
};

/*
  设备监控列表 — 获取大类
*/
async function getPageList() {
  try {
    pageLoading.value = true;
    deviceLoading.value = true;
    const { data } = await request({
      url: `/iotadmin/deviceMonitor/getEquipCategory`,
      method: "get",
      data: {},
    });
    pageList.value = data || {};
    if (pageList.value.length) {
      // handleSelect(activeIndex.value);
    } else {
      deviceLoading.value = false;
    }
    pageLoading.value = false;
  } catch (error) {
    pageLoading.value = false;
    deviceLoading.value = false;
  }
}

/*
  设备监控列表 — 获取位置列表
*/
const deviceList = ref(<any>[]);

async function getDeviceList(itemValue: string) {
  try {
    deviceLoading.value = true;
    // const { data } = await request({
    //   url: `/iotadmin/deviceMonitor/queryEquipLocation/${itemValue}`,
    //   method: "get",
    //   data: {},
    // });
    // deviceList.value = mockList;
    // deviceList.value = data;
    deviceLoading.value = false;
  } catch (error) {
    deviceLoading.value = false;
  }
}

/*
  跳转至实时监控详情页面
*/
function jumpUrl(item: any, text: any) {
  if (text === 4) {
    router.push({
      name: "PSMPSMPARAMMONITORINGLISTNEW",
      query: {
        equipCode: item.machineCode,
        equipId: item.machineId,
        processEquipId: item.processEquipId,
      },
    });
  } else if (text === 1) {
    router.push({
      name: "PSMPSMPARAMMONITORINGLIST",
      query: {
        equipCode: item.machineCode,
        equipId: item.machineId,
      },
    });
  } else {
    router.push({
      name: "PSMPSMPARAMMONITORINGDETAIL",
      query: {
        equipCode: item.machineCode,
        paramType: text,
      },
    });
  }
}

/*
  轮询定时器
*/
const timer = ref();
onMounted(() => {
  // getPageList();
  pageable.value.pageSize = 20;
  getTableList();
  timer.value = setInterval(() => getPageList(), 3 * 60 * 1000);
  getWorkshopIdList();
  getProcessCodeList();
  getEquipList();
  getWorkshopSectionList();
});

onBeforeUnmount(() => {
  clearInterval(timer.value);
});

function resetParams() {
  searchParam.value = searchParamInit;
  getEquipList();
  getProcessCodeList();
  reset();
}

// 请求参数
const requestApi = "/dmpDosPcm/processParamMonitor/queryProcessEquip";

// 是否需要分页
const pagination = true;

const initParam = reactive({});

// 初始化搜索参数数据
const searchParamInit = {
  workShopId: "",
  processId: "",
  processCode: "",
  processEquipId: "",
  deviceStatus: "",
  workshopSectionId: "",
};

// 数据请求错误后处理
function requestError() {
  // tableData.value = mockList1;
}

// 数据请求错误后处理
function dataCallBack(data: any) {
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

// const produceStatusList = ref([
//   {
//     value: 1,
//     label: "生产",
//   },
//   {
//     value: 2,
//     label: "停机",
//   },
//   {
//     value: 3,
//     label: "报警",
//   },
// ]);

const produceStatusList = ref(useDictionary("ProduceDeviceStatus"));

const workshopIdList: any = ref([]);
const processCodeList: any = ref([]);
async function getWorkshopIdList() {
  const { data } = await request({
    url: `/mdm/mdmworkshop/getList`,
    method: "post",
    data: {},
  });
  workshopIdList.value = data;
}

async function getProcessCodeList() {
  const { data } = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processCodeList.value = data;
}
function processChange(id: string) {
  searchParam.value.processEquipId = "";
  if (id) {
    const current: any =
      processCodeList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
    getEquipList();
  } else {
    searchParam.value.processCode = "";
    // equipList.value = [];
    // if (searchParam.value.workShopId) {
    getEquipList();
    // }
  }
}

function workShopChange(id: string) {
  searchParam.value.processEquipId = "";
  if (id) {
    getEquipList(id, searchParam.value.processId);
  } else {
    equipList.value = [];
    if (searchParam.value.processId) {
      getEquipList("", searchParam.value.processId);
    }
  }
}
// 通过工序查询设备列表
const equipList = ref(<any>[]);
// async function getEquipList(id: string, id1: string) {
//   equipList.value =
//     (await getMdmProcessEquipApi1({ workshopId: id, processId: id1 })) || [];
// }
async function getEquipList(id = "", id1 = "") {
  equipList.value = [];
  const res: any = await request({
    // url: "/iotadmin/scaequipinfo/getlist",
    // url: "/dmpDosPcm/equipmentInfo/getList",
    url: "/mdm/mdmprocessequip/getList",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
    },
  });
  if (res.code === 200) {
    equipList.value = res.data;
    filteredOptions.value = res.data;
  }
}
const filteredOptions = ref<any>([]);
// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...equipList.value];
    return;
  }
  filteredOptions.value = equipList.value.filter((option: any) =>
    option.equipName.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};
const changeWorkshopSection = () => {
  searchParam.value.processId = "";
  searchParam.value.processEquipId = "";
  processCodeList.value = [];
  getProcessListByWorkshopSection();
  getEquipList();
};
const getProcessListByWorkshopSection = async () => {
  if (searchParam.value.workshopSectionId) {
    await request({
      url: `mdm/mdmworkshopsection/getDetails`,
      method: "post",
      data: { id: searchParam.value.workshopSectionId },
    }).then((res) => {
      processCodeList.value = res.data
        ? res.data.map(({ processId, processCode }) => ({
            id: processId,
            processName: processCode,
          }))
        : [];
    });
  } else {
    await getProcessCodeList();
  }
};
function equipChange(id: string) {
  // if (id) {
  //   const current: any =
  //     equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
  //   searchParam.equipCode = current.equipCode || "";
  // } else {
  //   searchParam.equipCode = "";
  // }
}
</script>

<style lang="scss" scoped>
.table-container-scroll ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  li {
    display: inline-block;
    // width: 300px;
    flex-grow: 1;
    // cursor: pointer;
    margin: 5px;
    max-width: 350px;
    min-width: 300px;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    overflow: hidden;
    .greenFont {
      color: rgb(160, 230, 3);
    }
    .redFont {
      color: rgb(246, 64, 64);
    }
    .greyFont {
      color: grey;
    }
    .greenColor {
      color: darkslategrey;
      background: rgb(29, 233, 182);
    }
    .greenColor07 {
      color: darkslategrey !important;
      background: rgb(29, 233, 182, 0.2) !important;
    }
    .yellowColor07 {
      background: rgb(255, 255, 0, 0.2) !important;
    }
    .redColor {
      color: rgb(246, 64, 64) !important;
      background: #fef0f0 !important;
      .numberLight {
        color: rgb(246, 64, 64) !important;
      }
    }
    .greyColor {
      color: grey;
      background: rgba(0, 0, 0, 0.05);
    }
    .card-white-title {
      text-align: center;
      margin: 2px 2px 0;
      border-radius: 2px;
      padding: 10px 8px;
      font-size: 15px;
      font-weight: 600;
      display: flex;
      justify-content: space-between;
      position: relative;
    }
    .location-name {
      font-weight: 400;
      font-size: 14px;
    }
    p {
      padding: 0 14px;
      margin: 0;
      font-size: 13px;
      font-weight: 300;
      margin: 0;
      color: #86888a;
      overflow: hidden;
      line-height: 20px;
    }
    .card-item {
      position: relative;
      overflow: hidden;
      height: 100%;
      display: flex;
      flex-direction: column;
      cursor: pointer;
      .item_title {
        height: 38px;
        line-height: 38px;
        width: 100%;
        color: #31abe3;
        font-size: 16px;
        position: relative;
        z-index: 2;

        .title-inner {
          padding: 0;
          position: absolute;
          top: 27px;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 400;
          letter-spacing: 1px;
          background: #000;
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }
      .card-content {
        width: 100%;
        height: calc(100% - 38px - 6px);
        overflow: hidden;
        display: flex;
        align-items: center;
        .card-left {
          width: 50%;
          height: 100%;
          float: left;
          text-align: center;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          padding: 8px 0;
          .pic-type {
            position: relative;
            width: 90%;
            height: 100%;
            display: inline-block;
            svg {
              position: absolute;
              right: -15px;
              bottom: 0px;
              font-size: 28px;
              z-index: 9;
            }
            .coverImg {
              margin-top: 0;
              width: 100%;
              height: 100%;
              background-position: center;
              background-repeat: no-repeat;
              background-size: contain;
            }
            .nodataImg {
              background-image: url("../../../assets/images/no-device.png");
            }
          }

          .card-value {
            padding: 0 10px;
            span:nth-child(1) {
              display: block;
              margin-top: 5px;
              font-size: 16px;
              font-weight: 900;
              font-family: "DinLight";
            }
            span:nth-child(2) {
              display: block;
              font-size: 12px;
              line-height: 14px;
              margin-top: 5px;
            }
          }
        }
        .card-right {
          width: 50%;
          height: auto;
          padding-top: 8px;
          padding-bottom: 8px;
          float: right;
          .card-name {
            height: auto;
            margin-bottom: 5px;
            width: 95%;
            border: 1px solid #eee;
            background-color: rgba(172, 185, 227, 0.05);
            margin-left: 2%;
            padding: 5px 5px 5px;
            // display: flex;
            // justify-content: space-between;
            span {
              font-size: 12px;
              display: block;
              text-align: center;
              line-height: 15px;
              padding: 0;
              word-break: break-all;
              // flex: 1;
              width: auto;
            }
            .name-label {
              font-size: 12px;
              display: block;
              text-align: center;
              line-height: 15px;
              padding: 0;
              word-break: break-all;
              // flex: 1;
              width: auto;
              color: #86888a;
            }
            span:nth-child(1) {
              font-size: 12px;
              display: block;
              // min-width: 44px;
            }
            span:nth-child(2) {
              font-weight: 400;
              margin: 3px 0 2px;
              // margin-top: 3px;
              font-size: 13px;
              // line-height: 18px;
              display: block;
              font-family: DINAlt;
              color: rgb(49, 52, 59);
            }
          }
          .card-name:nth-last-child(1) {
            margin-bottom: 0px;
          }
        }
      }
    }
  }
  li:hover {
    // cursor: pointer;
    img {
      transform: scale(1.12);
    }
  }
}

.produce-c-title {
  font-weight: 600;
  margin: 20px 0 7px 20px;
  font-size: 16px;
  position: RELATIVE;
  padding-left: 15px;
  svg {
    width: 1em;
    height: 1em;
    font-size: 24px;
    transform: rotateZ(-268deg);
    position: absolute;
    left: -11px;
    top: -1px;
  }
}

.catalog {
  position: relative;
}

.catalog {
  :deep(.el-menu-item.is-active) {
    background-color: #2979ff !important;
    color: #fff !important;
  }
  :deep(.el-menu-item) {
    background-color: rgb(239, 240, 253) !important;
    font-size: 14px;
    margin-right: 10px;
    border-radius: 6px;
    width: auto;
    padding: 0px 30px;
    display: inline;
    line-height: 34px;
    border: none;
    float: left;
    margin-bottom: 10px;
  }
  :deep(.el-menu--horizontal.el-menu) {
    border-bottom: none !important;
    display: block !important;
    height: 34px;
    line-height: 34px;
  }
  :deep(.el-sub-menu) {
    color: #2979ff;
    background-color: transparent;
    width: 20px;
    float: left;
    display: inline;
    border: none;
    line-height: 34px;
    height: 34px;
    .el-icon {
      color: #2979ff;
      border: none;
    }
  }

  :deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title:hover) {
    background-color: transparent !important;
  }
  :deep(.el-sub-menu.is-active .el-sub-menu__title) {
    border-color: transparent !important;
  }
}
.el-menu--horizontal .el-menu .el-menu-item.is-active {
  background-color: rgb(239, 240, 253) !important;
  color: #2979ff !important;
  font-weight: bold !important;
}
.link-btn {
  color: rgb(49, 52, 59);
  text-decoration: underline;
}
.face_svg {
  font-size: 26px;
  position: absolute;
  right: 0;
  top: 8px;
}
</style>
